<?php
declare(strict_types=1);
/**
 * Created by PhpStorm.
 * User: wumengmeng <wu_mengmeng@foxmail.com>
 * Date: 2019/4/26 0026
 * Time: 11:18
 */

namespace Modules\SmallApi\Service;

use HiCommon\Repository\FeedbackRepository;
use HiCommon\Repository\UserInviteSetRepository;
use HiCommon\Repository\UserInviteRepository;
use HiCommon\Repository\BannerRepository;
use HiCommon\Repository\NoticeRepository;
use HiCommon\Repository\CollectRepository;
use HiCommon\Repository\UsersRepository;
use HiCommon\Repository\InviteRepository;
use HiCommon\Repository\CouponGrantDetailRepository;
use HiCommon\Repository\RepairstoreGoodsImgRepository;
use Modules\Api\Service\H5Service;

class FeedbackService extends BaseService
{

	/**
	 *	添加反馈信息
	 *	hinq 2019 09 02
	 *
	 **/
	public function add_one( array $arrInput ){
		try {
			if( empty( $arrInput['content'] ) ){
				return ['state'=> 1,'msg'=>'反馈信息不能为空','data'=>[],'error'=>''];
			}

			if( empty( $arrInput['contact'] ) ){
				return ['state'=> 1,'msg'=>'请填写联系方式','data'=>[],'error'=>''];
			}
			if( !preg_match("/^1[34578]{1}\d{9}$/",$arrInput['contact']) && !preg_match('/^[a-z0-9]+([._-][a-z0-9]+)*@([0-9a-z]+\.[a-z]{2,14}(\.[a-z]{2})?)$/i',$arrInput['contact']) ){
	            return ['state'=> 1,'msg'=>'联系方式不正确','data'=>[],'error'=>''];
			}
			$arrInput['user_id'] = small_api_user_id();
			$arrInput['state'] = 1;
			$res = FeedbackRepository::add_one( (array) $arrInput );
			$result = hi_check_res($res,'add_one');
	        if ($result['state'] != 0) {
	            return ['state'=> 1,'msg'=>'信息更新失败','data'=>[],'error'=>''];
	        }
	        return ['state'=> 0,'msg'=>'ok','data'=>[],'error'=>''];
		} catch (\Exception $exception) {
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }

	}


	/**
	 *	获取邀请设置的信息
	 *	hinq 2019 09 02
	 *	使用场景【 个人中心 邀请有礼】	
	 **/
	public function get_info(){
		try {
		    $uid = small_api_user_id();
			//获取邀请设置的信息
			$arr_where['field'] = ['p_num','num','id'];
			$arr_invite_info = UserInviteSetRepository::get_one( (int) 1 , (array) $arr_where );
			unset( $arr_invite_info['id'] );
			//获取当前用户已经邀请的用户数量
			$arr_where2['user_id'] = $uid;
			$arr_count = UserInviteRepository::get_count_by_where( (array) $arr_where2 );

			$temp['count'] = $arr_count;	
			$temp['get_count'] = intval( $arr_count / $arr_invite_info['p_num'] );

			$arr_list['set'] = $arr_invite_info;
			$arr_list['count'] = $temp;
            $arr_list['invite'] = H5Service::my_invite($uid);

	        return ['state'=> 0,'msg'=>'ok','data'=>$arr_list,'error'=>''];
		} catch (\Exception $exception) {
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
	}


	/**
	 *	获取首页banner图
	 *	hinq 2019 09 02
	 *	【应用场景 首页banner图】
	 **/
	public function get_all_banner(){
		try {
			//获取banner设置的信息
			$arr_where['field'] = ['p_num','num','id'];
			$arr_invite_info = UserInviteSetRepository::get_one( (int) 3 , (array) $arr_where );

			$arr_where['where'] = ["type"=>1,'status'=>1];
			$arr_where['order'] = ['key'=>'sort', 'value' => 'asc'];
			$arr_where['field'] = ['id','title','img','link_url'];
			//banner数据
			$res = BannerRepository::get_all_to_limit( (array) $arr_where , $arr_invite_info->p_num);
			//广告数据
			$arr_where['where'] = ["type"=>2,'status'=>1];
			$advert_list = BannerRepository::get_all_to_limit( (array) $arr_where , (int) 1 );

			foreach ($res as $key => &$value) {
				$value['img'] = oss_full_url( $value['img']);
			}

			foreach ($advert_list as $key => &$value) {
				$value['img'] = oss_full_url( $value['img']);
			}
			
			$result = hi_check_res($res,'get_one');
	        if ($result['state'] != 0) {
	            return ['state'=> 1,'msg'=>'获取失败','data'=>[],'error'=>''];
	        }
	        $temp['data'] = $res;
	        $temp['times'] = $arr_invite_info->num;
	        $temp['advert'] = $advert_list;
			return ['state'=> 0,'msg'=>'ok','data'=>$temp,'error'=>''];
		} catch (\Exception $exception) {
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
	}


	/**
	 *	获取公告列表数据
	 *	hinq 2019 09 02
	 *	使用场景【首页公告轮播】
	 **/
	public function get_all_notice(){
		try {
			$arr_where['order'] = ['key'=>'sort', 'value' => 'asc'];
			$arr_where['field'] = ['id','title','content','type'];
			$res = NoticeRepository::get_all_notice( (array) $arr_where );
			$result = hi_check_res($res,'get_one');
	        if ($result['state'] != 0) {
	            return ['state'=> 1,'msg'=>'获取失败','data'=>[],'error'=>''];
	        }
	        foreach ($res as $key => $value) {
	        	$temp = explode(',', $value['type']);
	        	if( !in_array( 1 , $temp) ){   // 1 => '小程序'
	        		unset($res[$key]);
	        	}
	        }
			return ['state'=> 0,'msg'=>'ok','data'=>$res,'error'=>''];
		} catch (\Exception $exception) {
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
	}


	/**
	 *	添加收藏功能
	 *	hinq 2019 09 05
	 *	id int  关注的对象id
	 **/
	public function add_one_collect( array $arrInput ){
		try {
			if( empty( $arrInput['x_id'] ) ){
	            return ['state'=> 1,'msg'=>'收藏对象不能为空','data'=>[],'error'=>''];
			}
			$arrInput['user_id'] = small_api_user_id();
			$count = CollectRepository::get_count_by_where( (array) $arrInput );
			if( $count >= 1 ){
				return ['state'=> 1,'msg'=>'您已收藏','data'=>[],'error'=>''];
			}
			// $arrInput['type'] = 1;
			$res = CollectRepository::add_one( (array) $arrInput );
			$result = hi_check_res($res,'add_one');
	        if ($result['state'] != 0) {
	            return ['state'=> 1,'msg'=>'收藏失败','data'=>[],'error'=>''];
	        }
	        return ['state'=> 0,'msg'=>'ok','data'=>[],'error'=>''];
		} catch (\Exception $exception) {
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
	}



	/**
	 *	收藏列表
	 *	hinq 2019 09 05
	 *	使用场景【 收藏列表 】
	 **/
	public function get_collect_list(){
		try {
			$arrInput['where'] = ['user_id'=>small_api_user_id()];
			$arrInput['with'] = ['GoodsInfo','RepairstoreGoods','GoodsInfo.product_info'];
			$arrInput['field'] = ['id','user_id','x_id','type'];
			$res = CollectRepository::get_list( (array) $arrInput );
			$data = $res->toArray()['data'];
			foreach ($data as $key => &$value) {
				if( $value['type'] == 2 ){    //维修店的商品
					//获取商品的图片信息
					$goods_img = RepairstoreGoodsImgRepository::get_list_by_where( (array) ['goods_id' => $value['x_id']] );
					$value['repairstore_goods']['pic_url'] = $goods_img[0]['picurl'];
					$value['repairstore_goods']['title'] = $value['repairstore_goods']['name'];
					$value['repairstore_goods']['integral'] = '';
					unset( $value['repairstore_goods']['name'] );
					$value['goods_info'] = $value['repairstore_goods'];
					unset( $value['repairstore_goods'] );
					unset( $value['repairstore_goods_img'] );

				}else if( $value['type'] == 1 ){   //积分的商品
				    if( isset( $value['goods_info'] ) && count( $value['goods_info']['product_info'] ) > 0 ){
                        $value['goods_info']['integral'] = $value['goods_info']['product_info'][ 0]['integral'];
                    }else{
                        $value['goods_info']['integral'] = 0;
                    }
					unset( $value['repairstore_goods'] );
                    unset( $value['repairstore_goods_img'] );
                    unset( $value['goods_info']['product_info'] );
				}
			}

			$temp = [
				'data' => $data,
				'page_data' => [
					'per_page' => $res->toArray()['per_page'],
					'current_page' => $res->toArray()['current_page'],
					'last_page' => $res->toArray()['last_page'],
					'total' => $res->toArray()['total'],
				]
			];
			$result = hi_check_res($res,'get_one');
	        if ($result['state'] != 0) {
	            return ['state'=> 1,'msg'=>'获取失败','data'=>[],'error'=>''];
	        }
	        return ['state'=> 0,'msg'=>'ok','data'=>$temp,'error'=>''];
		} catch (\Exception $exception) {
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
	}


	/**
	 *	删除收藏
	 *	hinq 2019 09 07
	 *	使用场景【 个人中心  收藏 收藏列表】
	 **/
	public function del_collect( array $arr_input ){
		try {
			if( empty( $arr_input ) ){
	            return ['state'=> 1,'msg'=>'参数不能为空','data'=>[],'error'=>''];
			}
			if( !empty( $arr_input['id'] ) ){   //有主键id
				$arr_where['id'] = $arr_input['id'];
				$arr_where['user_id'] = small_api_user_id();
				$arr_where['type'] = $arr_input['type'];


				$count = CollectRepository::get_count_by_where( (array) $arr_where );
				
				if( $count == 0 ){
		            return ['state'=> 1,'msg'=>'参数错误','data'=>[],'error'=>''];
				}
				$res = CollectRepository::delete_one( (int) $arr_input['id'] );
				$result = hi_check_res($res,'delete_one');
		        if ($result['state'] != 0) {
		            return ['state'=> 1,'msg'=>'删除失败','data'=>[],'error'=>''];
		        }
			}else if( !empty( $arr_input['x_id'] ) ){
				$arr_where['x_id'] = $arr_input['x_id'];
				$arr_where['user_id'] = small_api_user_id();
				$arr_where['type'] = $arr_input['type'];
				$count = CollectRepository::get_count_by_where( (array) $arr_where );
				if( $count == 0 ){
		            return ['state'=> 1,'msg'=>'参数错误','data'=>[],'error'=>''];
				}
				$res = CollectRepository::delete_one_to_where( (array) $arr_where );
				$result = hi_check_res($res,'delete_one');
		        if ($result['state'] != 0) {
		            return ['state'=> 1,'msg'=>'删除失败','data'=>[],'error'=>''];
		        }
			}

	        return ['state'=> 0,'msg'=>'ok','data'=>$res,'error'=>''];
		} catch (\Exception $exception) {
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }

	}


	/**
	 *	设置订单助手
	 *	hinq 2019 09 07
	 *	使用场景【 个人中心 设置 系统设置 订单助手】
	 **/
	public function set_order_helper( array $arrInput ){
		try {
			if( empty( $arrInput ) && $arrInput != 0 ){
				return ['state'=> 1,'msg'=>'参数错误','data'=>[],'error'=>''];
			}
			$arrInput['id'] = 2;
			$res = UserInviteSetRepository::edit_one( (array) $arrInput );
			$result = hi_check_res($res,'edit_one');
	        if ($result['state'] != 0) {
	            return ['state'=> 1,'msg'=>'编辑失败','data'=>[],'error'=>''];
	        }
	        return ['state'=> 0,'msg'=>'ok','data'=>[],'error'=>''];
		} catch (\Exception $exception) {
            return ['state'=>1,'msg'=>$exception->getMessage()];
        }
	}


	/**
	 *	获取订单助手设置
	 *	hinq 2019 09 07
	 *
	 **/
	public function get_order_helper(){
		$arr_where['field'] = ['p_num'];
		$res = UserInviteSetRepository::get_one( (int) 2 , (array) $arr_where );
		$result = hi_check_res($res,'get_one');
        if ($result['state'] != 0) {
            return ['state'=> 1,'msg'=>'获取失败','data'=>[],'error'=>''];
        }
        return ['state'=> 0,'msg'=>'ok','data'=>$res,'error'=>''];
	}



	/**
	 *	用户分享达到要求后赠送优惠券，并添加邀请记录
	 *	hinq 2019 09 09
	 *	使用场景  【用户注册 有上级对象时  调用】
	 *	$user_id int 邀请者id
	 *	$to_user_id int 被邀请者id
	 *	接口位置  FeedbackService::send_coupon_to_user( int $user_id = null , int $to_user_id = null )
     *  1：邀请者和被邀请者只能有一条数据 
     *  2：被邀请者只能被邀请一次
	 *  3：邀请累计的人数达不到系统设置的人数 不发放优惠券
	 **/
	public function send_coupon_to_user( int $user_id = null , int $to_user_id = null ){

		if( empty( $user_id ) && empty( $to_user_id ) ){
			return ['state'=> 1,'msg'=>'参数不能为空','data'=>[],'error'=>''];
		}

		//验证邀请者和被邀请者是否重复添加数据
		$arr_where['user_id'] = $user_id;   
		$arr_where['to_user_id'] = $to_user_id;   
		$count = InviteRepository::get_count_by_where( (array) $arr_where );
		if( $count >= 1 ){
			return ['state'=> 1,'msg'=>'请勿重复添加数据','data'=>[],'error'=>''];
		}

		//验证被邀请者是否已经存在
		$count = InviteRepository::get_count_by_where( (array) ['to_user_id'=>$to_user_id] );
		if( $count >= 1 ){
			return ['state'=> 1,'msg'=>'被邀请者已被邀请','data'=>[],'error'=>''];
		}

		//添加分享记录
		InviteRepository::add_one( (array) $arr_where );
		
		//统计当前用户分享的总人数
		unset( $arr_where['to_user_id']);
		$count = InviteRepository::get_count_by_where( (array) $arr_where );

		//获取设置的分享信息数据
		$where['field'] = ['p_num','num','id','coupon_id'];
		$where['with'] = ['getCoupon'];     //这里需要关联一下优惠券的信息
		$arr_info = UserInviteSetRepository::get_one( (int) 1 , (array) $where );

		if( $count < $arr_info['p_num'] ){
	        return ['state'=> 0,'msg'=>'不满足发放条件','data'=>[],'error'=>''];
		}

		//获取当前分享用户的信息
		$arr_where_user['field'] = ['id','integral'];  
		$arr_user_info = UsersRepository::get_all_by_where( (array) [ 'id' => $user_id ] ,(array) $arr_where_user );

		//已发放的张数
		$map['user_id'] = $arr_user_info[0]['id'];
		// $map['coupon_id'] = $arr_info['coupon_id'];  //这里是隐形的bug  如果后台更改了优惠券 算法就会出错
		$map['type'] = 2;
		$send_count = CouponGrantDetailRepository::get_count_by_where( (array) $map );

		//	5              ==       12         -    5       *   1          
		//设置的分享总人数   ==  已成功分享的人数  - 设置总人数  * 已领取的张数
		if( $arr_info['p_num']  == $count - $arr_info['p_num'] * $send_count ){
			//这里需要给分享的用户赠送一张分享的优惠券
			$temp['user_id'] = $user_id;
			$temp['coupon_id'] = $arr_info['coupon_id'];
			$temp['pid'] = $arr_info['getCoupon']['pid'];
			$temp['over_at'] = time() + $arr_info['getCoupon']['validity_at'] * 3600 * 24;
			$temp['ticket_num'] = set_coupons_ticket_num( $arr_info['getCoupon']['pid'] );
			$temp['msg'] = '分享好友获得优惠券';
			$temp['integral'] = $arr_user_info[0]['integral'];
			$temp['status'] = 1;
			$temp['type'] = 2;
			$res = CouponGrantDetailRepository::add_one( (array) $temp );
			$result = hi_check_res($res,'add_one');
	        if ($result['state'] != 0) {
	            return ['state'=> 1,'msg'=>'发放失败','data'=>[],'error'=>''];
	        }
	        return ['state'=> 0,'msg'=>'ok','data'=>[],'error'=>''];
		}else{
	        return ['state'=> 0,'msg'=>'不满足发放条件','data'=>[],'error'=>''];
		}
	}



	/**
	 *	获取已经开通城市的列表
	 *	hinq 2019 09 09
	 *	使用场景 【 首页定位页使用】
	 **/
	// public function get_city_list(){
		
		
	// }

    /**
     *	获取vip升级提示信息
     *	hinq 2019 09 09
     *
     **/
    public function protocol_vip(){
        return \Modules\Api\Service\FeedbackService::protocol_vip();
    }

}